# -*- coding: utf-8 -*-
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator

from dvadmin.design.models import NodeTypes, NodesHierarchy
from dvadmin.utils.json_response import SuccessResponse, DetailResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.validator import CustomUniqueValidator
from dvadmin.utils.viewset import CustomModelViewSet


class NodeTypesSerializer(CustomModelSerializer):
    """
    业务类型-序列化器
    """

    class Meta:
        model = NodeTypes
        fields = "__all__"


class NodeTypesInitSerializer(CustomModelSerializer):
    """
    业务类型-初始化(用于生成初始化json文件)
    """

    class Meta:
        model = NodeTypes
        fields = ['description']
        read_only_fields = ["id"]
        extra_kwargs = {
            'creator': {'write_only': True},
            'dept_belong_id': {'write_only': True}
        }


class NodeTypesCreateUpdateSerializer(CustomModelSerializer):
    """
    业务类型-创建/更新时的列化器
    """
    description = serializers.CharField(max_length=255, validators=[CustomUniqueValidator(queryset=NodeTypes.objects.all(), message="业务类型必须唯一")])

    def validate(self, attrs: dict):
        return super().validate(attrs)

    def save(self, **kwargs):
        data = super().save(**kwargs)
        data.save()
        return data

    class Meta:
        model = NodeTypes
        fields = '__all__'


class NodeTypesViewSet(CustomModelViewSet):
    """
    业务类型-接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = NodeTypes.objects.all()
    serializer_class = NodeTypesSerializer
    create_serializer_class = NodeTypesCreateUpdateSerializer
    update_serializer_class = NodeTypesCreateUpdateSerializer
    search_fields = ['description']
    filter_fields = ['description']


class NodesHierarchySerializer(CustomModelSerializer):
    """
    业务树-序列化器
    """
    parent_name = serializers.CharField(read_only=True, source='parent.name')
    hasChild = serializers.SerializerMethodField()

    def get_hasChild(self, instance):
        hasChild = NodesHierarchy.objects.filter(parent=instance.id)
        if hasChild:
            return True
        return False

    class Meta:
        model = NodesHierarchy
        fields = '__all__'
        read_only_fields = ["id"]


class NodesHierarchyInitSerializer(CustomModelSerializer):
    """
    递归深度获取数信息(用于生成初始化json文件)
    """
    children = serializers.SerializerMethodField()

    def get_children(self, obj: NodesHierarchy):
        data = []
        instance = NodesHierarchy.objects.filter(parent_id=obj.id)
        if instance:
            serializer = NodesHierarchyInitSerializer(instance=instance, many=True)
            data = serializer.data
        return data

    def save(self, **kwargs):
        instance = super().save(**kwargs)
        children = self.initial_data.get('children')
        if children:
            for menu_data in children:
                menu_data['parent'] = instance.id
                filter_data = {
                    "name": menu_data['name'],
                    "parent": menu_data['parent']
                }
                if 'key' in menu_data:
                    filter_data['key'] = menu_data['key']
                instance_obj = NodesHierarchy.objects.filter(**filter_data).first()
                if instance_obj and not self.initial_data.get('reset'):
                    continue
                serializer = NodesHierarchyInitSerializer(instance_obj, data=menu_data, request=self.request)
                serializer.is_valid(raise_exception=True)
                serializer.save()

        return instance

    class Meta:
        model = NodesHierarchy
        fields = ['name', 'parent', 'node_type_id', 'node_order','children']
        extra_kwargs = {
            'creator': {'write_only': True},
            'dept_belong_id': {'write_only': True}
        }
        read_only_fields = ['id', 'children']


class NodesHierarchyCreateUpdateSerializer(CustomModelSerializer):
    """
    业务树 创建/更新时的列化器
    """

    def create(self, validated_data):
        instance = super().create(validated_data)
        instance.save()
        return instance

    class Meta:
        model = NodesHierarchy
        fields = '__all__'


class NodesHierarchyViewSet(CustomModelViewSet):
    """
    业务树-接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = NodesHierarchy.objects.all()
    serializer_class = NodesHierarchySerializer
    create_serializer_class = NodesHierarchyCreateUpdateSerializer
    update_serializer_class = NodesHierarchyCreateUpdateSerializer
    search_fields = ['name', 'parent']
    filter_fields = ['name', 'parent']

